import collections
class Solution(object):
    def largestValsFromLabels(self, values, labels, numWanted, useLimit):
        n = len(labels)
        t = [[values[i], labels[i]] for i in range(n)]
        t.sort(reverse=True)
        count = 0
        d = collections.defaultdict(int)
        ans = 0
        for v, l in t:
            if d[l] + 1 <= useLimit:
                d[l] += 1
                ans += v
                count += 1
                if count == numWanted:
                    return ans
        return ans

